// pages/home/home.js
var app = getApp()
var mqtt = require('../../utils/mqtt.js');
//一个全局变量...
var client = null;
//一个全局变量...
let socketOpen = false
// const ApiRootUrl = 'http://localhost:8001/';
const ApiRootUrl = 'http://8.136.195.245:8000/';
Page({
  data: {
    scanStr: "",
    androidDialog2: false,
    androidDialog2_Scanpay: false,
    resmsg: "",
    cardUid: "",
    toast: false,
    warnToast: false,

    hideToast: false,
    hideWarnToast: false,
    warn401Toast: false,
    hide401Toast: false,

  },

  // 扫码投递
  getScancode() {
    var that = this
    wx.scanCode({
      success(res) {
        console.log("res=", res)
        console.log("res.result=", res.result)
        // console.log("type=", typeof (res.result))
        // console.log("type=", typeof (JSON.parse(res.result)))
        that.setData({
          scanStr: res.result,
          cardUid: res.result,
          // binNumber: JSON.parse(res.result).binNumber,
          // time: JSON.parse(res.result).time,
          androidDialog2: true
        })
      }
    })
  },

  // 绑定用户
  navigatetoPayrecord() {
    wx.navigateTo({
      url: '/pages/payRecord/payRecord',
    })
  },

  // 上门服务
  getService() {
    wx.navigateTo({
      url: '/pages/service/service',
    })
  },
  // 绑定用户和卡片，生成一条卡片绑定记录
  bindUser: function () {
    let that = this
    console.log("你在进行api请求")
    console.log("userid:", app.globalData.userId)
    console.log("carduid:", that.data.cardUid)
    console.log("typeOfuserid:", typeof (app.globalData.userId))
    wx.request({
      // url: 'http://8.136.195.245:8000/card/bindUser',
      // url: 'http://localhost:8001/card/bindUser',
      url:ApiRootUrl+'card/bindUser',
      data: {
        cardUid: that.data.cardUid,
        userId: app.globalData.userId,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'chartset': 'utf-8'
      },
      success(res) {
        console.log("获取数据成功", res)
        console.log("code:", res.data.code)
        that.connectMqtt_bindUser(res.data.code)
        that.setData({
          msg: res.data.message,
          // toast: res.data.code
        })
        console.log("res.data.data", res.data.message)

        if (res.data.code == 200) {
          that.openToast()
        }
        if (res.data.code == 400) {
          that.openWarnToast()
        }
        if (res.data.code == 401) {
          that.open401Toast()
        }
        
      }
    })
  },
  close: function () {
    this.setData({
      androidDialog2: false,
    })

  },
  confirm: function () {
    console.log("你点击了确定充值按钮")
    this.setData({
      androidDialog2: false,
    })
    this.bindUser()
  },


  // 扫码支付，获取oled上二维码包含的水果名、重量、单价信息、总价信息
  scanPaycode() {
    var that = this
    wx.scanCode({
      success(res) {
        console.log("res.result=", res.result)
        var splitStr = res.result.split("+")
        console.log("fruitName=", splitStr[0])
        console.log("unitPrice=", splitStr[2])
        console.log("type=", typeof (splitStr[2]))
        that.setData({
          scanStr: res.result,
          fruitName: splitStr[0],
          fruitWeight: splitStr[1],
          unitPrice: splitStr[2],
          totalPrice: splitStr[3],
          androidDialog2_Scanpay: true
        })
      }
    })
  },
  //调用api生成订单记录
  scanPay: function () {
    let that = this
    console.log("你在进行api请求")
    console.log("userid:", app.globalData.userId)
    // console.log("carduid:", that.data.cardUid)
    // console.log("typeOfuserid:", typeof (app.globalData.userId))
    wx.request({
      // url: 'http://8.136.195.245:8000/card/bindUser',
      // url: 'http://localhost:8001/orders/payOrder',
      url:ApiRootUrl+'orders/payOrder',
      data: {
        userId: app.globalData.userId,
        buyWay: 2,
        payWay: 2,
        fruitName: that.data.fruitName,
        fruitWeight: that.data.fruitWeight,
        unitPrice: that.data.unitPrice,
        totalPrice: that.data.totalPrice
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'chartset': 'utf-8'
      },
      success(res) {
        console.log("获取数据成功", res)
        console.log("code:", res.data.code)
        that.setData({
          msg: res.data.message
        })
        console.log("res.data.message", res.data.message)
        that.connectMqtt_scanpay(res.data.code)
        if (res.data.code == 200) {
          that.openToast()
        }
        if (res.data.code == 400) {
          that.openWarnToast()
        }
        if (res.data.code == 401) {
          that.open401Toast()
        }
      }
    })
  },
  closeScanpay: function () {
    this.setData({
      androidDialog2_Scanpay: false,
    })
    this.connectMqtt_scanpay(401 + "")

  },
  confirmScanpay: function () {
    console.log("你点击了确定支付按钮")
    this.setData({
      androidDialog2_Scanpay: false,
    })
    this.scanPay()
  },

  //调用接口，绑定用户后，返回信息到mqtt说明绑定状态，200成功、400其他失败、401该卡已被绑定
  connectMqtt_bindUser: function (code) {
    console.log("mqttcode=", code)
    const options = {
      connectTimeout: 4000, // 超时时间
      clientId: 'wx_' + parseInt(Math.random() * 100 + 800, 10),
      port: 8083, //重点注意这个,坑了我很久,一定是8083不是1883也不是443
      // username: 'xxx',
      // password: 'xxx',
    }

    client = mqtt.connect('wx://8.136.195.245/mqtt', options)
    client.on('reconnect', (error) => {
      console.log('正在重连:', error)
    })

    client.on('error', (error) => {
      console.log('连接失败:', error)
    })

    let that = this;
    client.on('connect', (e) => {
      console.log('成功连接服务器')
    })
    //发布绑定状态到mqtt的topic
    client.publish('fruit', code + "")
    console.log('发布至fruit' + code + "");
  },


  //调用接口，扫码后，返回信息到mqtt说明支付状态，200成功、400失败、401用户未支付
  connectMqtt_scanpay: function (code) {
    const options = {
      connectTimeout: 4000, // 超时时间
      clientId: 'wx_' + parseInt(Math.random() * 100 + 800, 10),
      port: 8083, //重点注意这个,坑了我很久,一定是8083不是1883也不是443
      // username: 'xxx',
      // password: 'xxx',
    }

    client = mqtt.connect('wx://8.136.195.245/mqtt', options)
    client.on('reconnect', (error) => {
      console.log('正在重连:', error)
    })

    client.on('error', (error) => {
      console.log('连接失败:', error)
    })

    let that = this;
    client.on('connect', (e) => {
      console.log('成功连接服务器')
    })
    //发布绑定状态到mqtt的topic
    client.publish('fruit', code + "")
    console.log('发布至fruit:' + code + "");
  },

  //成功弹窗
  openToast: function () {
    this.setData({
      toast: true
    });
    setTimeout(() => {
      this.setData({
        hideToast: true
      });
      setTimeout(() => {
        this.setData({
          toast: false,
          hideToast: false,
        });
      }, 300);
    }, 3000);
  },
  //操作失败弹框
  openWarnToast: function () {
    this.setData({
      warnToast: true
    });
    setTimeout(() => {
      this.setData({
        hidewarnToast: true
      });
      setTimeout(() => {
        this.setData({
          warnToast: false,
          hidewarnToast: false,
        });
      }, 300);
    }, 3000);
  },
  //该卡已被绑定的提示弹框
  open401Toast: function () {
    this.setData({
      warn401Toast: true
    });
    setTimeout(() => {
      this.setData({
        hide401Toast: true
      });
      setTimeout(() => {
        this.setData({
          warn401Toast: false,
          hide401Toast: false,
        });
      }, 300);
    }, 3000);
  },
})